/*
 * Copyright (C) 2011 Mette Bank, Rikke Jensen, Kenneth Brodersen, Thomas Pedersen
 * 
 * This file is part of digiPECS.
 * 
 * digiPECS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * digiPECS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with digiPECS.  If not, see <http://www.gnu.org/licenses/>.
 */

package sw6.digipecs.model;

import java.util.ArrayList;

import sw6.digipecs.R;
import sw6.digipecs.database.DBAdapter;
import sw6.digipecs.database.SentenceBoardStateCursor;
import sw6.digipecs.exceptions.DatabaseException;
import sw6.digipecs.exceptions.IDNotFoundException;
import sw6.digipecs.exceptions.ImageIsEmptyException;
import sw6.digipecs.helpers.ToastHelper;
import android.content.Context;
import android.util.Log;

/**
 * Class used to list all extended images that is shown in the sentence board.
 * The class will keep a list of the pictures currently in the sentence board,
 *  and will ensure that the data associated with each extended image is saved as 
 *  persistent data in a sqllitedatabase, which later to be resumed accordingly to an
 *  activity's life cycle.
 */
public class SentenceBoardList {	
	private final int mMaxPictures;
	private ArrayList<ExtImageInSentenceBoard> mImagesInBoard;
	
	//Database helper to save state of sentenceboard;
	private DBAdapter mDb;
	private Context mContext;
	

	/**
	 * Constructor - takes the context for use of database and 
	 * an integer to indicate how many pictures will be shown
	 * in the sentence board.
	 * @param context - the context that we work within
	 * @param maxPic - number of maximum pictures shown in the
	 * sentence board.
	 */
	public SentenceBoardList(Context context, int maxPic){
		mMaxPictures = maxPic;
		mImagesInBoard = new ArrayList<ExtImageInSentenceBoard>(mMaxPictures);
		mDb = new DBAdapter(context);
		mContext = context;
		
		for (; maxPic > 0; maxPic--) {
			mImagesInBoard.add(new ExtImageInSentenceBoard(context));
		}
	}
	/**
	 * Will get a list of all extend images stored in the sentence board
	 * @return ArrayList<ExtImage> - will return an Arraylist of ExtImages in the sentence board
	 */
	public ArrayList<ExtImageInSentenceBoard> getmImagesInBoard() {
		return mImagesInBoard;
	}
	/**
	 * Will set an extend image in the sentence board, to a specified location.
	 * @param location - an int used to specify the location of the picture in the sentence board.
	 * @param picture - the ExtImage that has to be stored in the sentence board
	 * @throws IndexOutOfBoundsException - in case that the array of extend images do not have the specified location in list of extended images.
	 */
	public void setPicture(int location, ExtImage picture) throws IndexOutOfBoundsException {
		ExtImageInSentenceBoard eisb;
		
		try {
			eisb = new ExtImageInSentenceBoard(mContext, picture.getId());
			mImagesInBoard.set(location, eisb);
		} catch (IDNotFoundException e) {
			Log.e("sw6", "This should not have been possible (see stacktrace)");
			e.printStackTrace();
		} catch (ImageIsEmptyException e) { }
	}
	/**
	 * Will get an extend image specified by the location in the
	 * gridView in the sentence board
	 * @param location - an int used to specify the location of the picture in the sentence board.
	 * @return ExtImage - the extended image found at the specified location
	 * @throws IndexOutOfBoundsException - in case no image is found at the location
	 */
	public ExtImage getPicture(int location) throws IndexOutOfBoundsException{
		return mImagesInBoard.get(location);
	}
	/**
	 * Will clear an extended image from the sentence board specified by the
	 * location of the picture.
	 * @param location - an int used to specify the location of the picture in the sentence board that will be cleared.
	 * @throws IndexOutOfBoundsException - in case that no image is found at this location
	 */
	public void clearPicture(int location) throws IndexOutOfBoundsException {
		mImagesInBoard.set(location, new ExtImageInSentenceBoard(mContext));
	}
	
	/**
	 * Method to call if the wish is to save the state of the sentence
	 * board. Will make the list of images and associated data persistent 
	 * by saving the data to a database.
	 */
	public void saveState(){
		Log.i("sw6", "Saving sentence board state");
		mDb.open();
		final int size = mImagesInBoard.size();
		mDb.clearSentenceBoardState();
		
		// Save every image in the sentence board unless the image is empty 
		for(int index = 0; index < size; index++){
			final ExtImage ext = this.getPicture(index);
			try {
				final int id = ext.getId();
				mDb.saveSentenceBoardStateItem(index, id);
			} catch (DatabaseException e) {
				ToastHelper.showError(mContext, R.string.errorSaveSentenceDB);
				e.printStackTrace();
			} catch (ImageIsEmptyException e) { }
		}
		
		mDb.close();
	}
	
	/**
	 * Method used to restore the last saved state of the sentence board. 
	 * Will make a call to the database where the information of the last
	 * saved list of images from the sentence board is kept.
	 */
	public void restoreState(){
		Log.i("sw6", "Restoring sentence board state");
		
		mDb.open();
		//cursor need for access to table in the database
		SentenceBoardStateCursor sbCursor = mDb.fetchSentenceBoardAllItems();
		Log.i("sw6", "Number of rows in the sentence board cursor: " + String.valueOf(sbCursor.getCount()));
		
		if (sbCursor.moveToFirst()) {
			do {
				// Retrieve data from the database
				final int id = sbCursor.getSentenceBoardStatePictureID();
				final int index = sbCursor.getSentenceBoardStateIndex();

				// Create and set image
				try {
					final ExtImageInSentenceBoard restoredImage = new ExtImageInSentenceBoard(mContext, id, index);
					if (index < mMaxPictures) mImagesInBoard.set(index, restoredImage);
				} catch (IDNotFoundException e) {
					ToastHelper.showError(mContext, R.string.errorLoadSentenceDB);
					e.printStackTrace();
				}
			} while (sbCursor.moveToNext());
		}
		
		sbCursor.close();
		mDb.close();
	}
	
	public void clearAll() {
		for (int i = mMaxPictures - 1; i >= 0; i--) {
			if (!mImagesInBoard.get(i).isLocked()) {
				mImagesInBoard.set(i, new ExtImageInSentenceBoard(mContext));
			}
		}
	}
}
